import { computed, ref } from 'vue';

/**
 * 加载状态管理 Composable
 * @param {boolean} initialState - 初始加载状态
 * @returns {Object} 加载状态管理对象
 */
export function useLoading(initialState = false) {
    const isLoading = ref(initialState);
    const loadingCount = ref(0);

    /**
     * 开始加载
     */
    const startLoading = () => {
        loadingCount.value++;
        isLoading.value = true;
    };

    /**
     * 结束加载
     */
    const stopLoading = () => {
        loadingCount.value = Math.max(0, loadingCount.value - 1);
        if (loadingCount.value === 0) {
            isLoading.value = false;
        }
    };

    /**
     * 重置加载状态
     */
    const resetLoading = () => {
        loadingCount.value = 0;
        isLoading.value = false;
    };

    /**
     * 包装异步函数，自动管理加载状态
     * @param {Function} asyncFn - 异步函数
     * @returns {Function} 包装后的函数
     */
    const withLoading = (asyncFn) => {
        return async (...args) => {
            try {
                startLoading();
                const result = await asyncFn(...args);
                return result;
            } finally {
                stopLoading();
            }
        };
    };

    return {
        isLoading: computed(() => isLoading.value),
        startLoading,
        stopLoading,
        resetLoading,
        withLoading
    };
}

/**
 * 多个加载状态管理 Composable
 * @returns {Object} 多加载状态管理对象
 */
export function useMultipleLoading() {
    const loadingStates = ref({});

    /**
     * 设置特定key的加载状态
     * @param {string} key - 状态键
     * @param {boolean} loading - 加载状态
     */
    const setLoading = (key, loading) => {
        loadingStates.value[key] = loading;
    };

    /**
     * 获取特定key的加载状态
     * @param {string} key - 状态键
     * @returns {boolean} 加载状态
     */
    const getLoading = (key) => {
        return loadingStates.value[key] || false;
    };

    /**
     * 检查是否有任何加载状态
     * @returns {boolean} 是否有加载中的状态
     */
    const hasAnyLoading = computed(() => {
        return Object.values(loadingStates.value).some(loading => loading);
    });

    /**
     * 清除所有加载状态
     */
    const clearAll = () => {
        loadingStates.value = {};
    };

    /**
     * 包装异步函数，自动管理特定key的加载状态
     * @param {string} key - 状态键
     * @param {Function} asyncFn - 异步函数
     * @returns {Function} 包装后的函数
     */
    const withKeyLoading = (key, asyncFn) => {
        return async (...args) => {
            try {
                setLoading(key, true);
                const result = await asyncFn(...args);
                return result;
            } finally {
                setLoading(key, false);
            }
        };
    };

    return {
        loadingStates: computed(() => loadingStates.value),
        setLoading,
        getLoading,
        hasAnyLoading,
        clearAll,
        withKeyLoading
    };
}

/**
 * 分页加载管理 Composable
 * @param {Function} fetchFn - 获取数据的函数
 * @param {Object} options - 配置选项
 * @returns {Object} 分页加载管理对象
 */
export function usePaginatedLoading(fetchFn, options = {}) {
    const {
        pageSize = 20,
        initialPage = 1,
        autoLoad = true
    } = options;

    const items = ref([]);
    const currentPage = ref(initialPage);
    const totalPages = ref(0);
    const totalCount = ref(0);
    const hasMore = ref(true);
    const { isLoading, withLoading } = useLoading();

    /**
     * 加载数据
     * @param {number} page - 页码
     * @param {boolean} append - 是否追加到现有数据
     */
    const loadData = withLoading(async (page = currentPage.value, append = false) => {
        try {
            const result = await fetchFn({
                page,
                pageSize: pageSize,
                offset: (page - 1) * pageSize
            });

            if (result && result.Data) {
                const newItems = Array.isArray(result.Data) ? result.Data : result.Data.items || [];

                if (append) {
                    items.value.push(...newItems);
                } else {
                    items.value = newItems;
                }

                currentPage.value = page;
                totalCount.value = result.Data.total || result.Total || 0;
                totalPages.value = Math.ceil(totalCount.value / pageSize);
                hasMore.value = page < totalPages.value;
            }
        } catch (error) {
            console.error('Failed to load data:', error);
            throw error;
        }
    });

    /**
     * 加载下一页
     */
    const loadMore = () => {
        if (hasMore.value && !isLoading.value) {
            return loadData(currentPage.value + 1, true);
        }
    };

    /**
     * 刷新数据
     */
    const refresh = () => {
        return loadData(1, false);
    };

    /**
     * 跳转到指定页
     * @param {number} page - 页码
     */
    const goToPage = (page) => {
        if (page >= 1 && page <= totalPages.value) {
            return loadData(page, false);
        }
    };

    // 自动加载初始数据
    if (autoLoad) {
        loadData();
    }

    return {
        items: computed(() => items.value),
        currentPage: computed(() => currentPage.value),
        totalPages: computed(() => totalPages.value),
        totalCount: computed(() => totalCount.value),
        hasMore: computed(() => hasMore.value),
        isLoading,
        loadData,
        loadMore,
        refresh,
        goToPage
    };
}
